#!/bin/bash
readonly PWD0=$(readlink -fn "$(dirname "$0")")

function LOG_debug() {
  echo -e "\033[1;35m[DEBUG]" "$@" "\033[0m"
}

function LOG_info() {
  echo -e "\033[1;36m[INFO]" "$@" "\033[0m"
}

function LOG_warn() {
  echo -e "\033[1;33m[WARN]" "$@" "\033[0m"
}

function LOG_error() {
  echo -e "\033[1;31m[ERROR]" "$@" "\033[0m"
}

function LOG_fatal() {
  echo -e "\033[1;31m[FATAL]" "$@" "\033[0m"
  exit 1
}

### NEEDED ENV:
### ASN1C_BIN          asn1c binary
### ASN1C_SUPPORT_PATH asn1c support path

### ARG1           : asn file directory
### OUTPUT PATH    : current directory
### OUTPUT sub dir : asncodec

function main() {
  set -e
  if [[ -z "${ASN1C_BIN}" ]]; then
    ASN1C_BIN=$(command -v asn1c) || LOG_fatal "Cannot find command: asn1c"
  fi
  if [[ $# -eq 0 ]]; then
    LOG_fatal "Need a param"
  fi
  local asn_file_path="$1"
  shift
  if [[ ! -x "${ASN1C_BIN}" ]]; then
    LOG_fatal "Failed to run asn1c: ${ASN1C_BIN}"
  fi
  if [[ -e "asncodec" ]]; then
    if [[ -e "asncodec/.asn-compile-ok" ]]; then
      LOG_info "'${PWD}/asncodec' is already exist, Skip."
      return 0
    fi
    rm -rf asncodec
  fi
  mkdir -p asncodec
  cd asncodec

  IFS=" " read -r -a asn_files <<<"$(
    find "$(readlink -fn "${asn_file_path}")" -type f -name "*.asn" |
      tr '\n' ' '
  )"

  ### ASN1 Compile
  declare -a asn1c_params=(
    -fcompound-names
    -fincludes-quoted
    -no-gen-example
  )
  if [[ -n "${ASN1C_SUPPORT_PATH}" ]]; then
    asn1c_params=(
      "${asn1c_params[@]}"
      -S "${ASN1C_SUPPORT_PATH}"
    )
  fi

  ${ASN1C_BIN} "${asn1c_params[@]}" "${asn_files[@]}" 2>/dev/null
  sed -i "s/18446744073709551615/18446744073709551615ULL/g" ./*
  [[ -e Makefile.am.libasncodec ]] && rm Makefile.am.libasncodec
  touch .asn-compile-ok
}
main "$@"
